<?php

namespace App\Services\CountGoldChildren;

use Carbon\Carbon;
use App\Models\User;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

class CountGoldChildren
{
	protected function allStormChildrenCount(User $user)
	{
		return $user->children()
			->where('grade', 'vip')
			->where('is_locked', false)
			->whereDate('created_at', '<', Carbon::today())
			->whereHas('goldRecords', function (Builder $query) {
				$query->whereDate('created_at', '<', Carbon::today())->whereNotNull('paid_at');
			})->count();
	}
	
	protected function moreThanLastDayCount(User $user, int $all)
	{
		$last = $user->goldChildren()->whereDate('created_at', Carbon::yesterday())->first();
		return $last ? $all - $last->records_children_count : 0;
	}
	
	protected function moreThanFirstDayCount(User $user, int $all)
	{
		$first = $user->goldChildren()->orderBy('id')->first();
		return $first ? $all - $first->records_children_count : 0;
	}
	
	public function count()
	{
		User::query()
			->chunks(50, function (Collection $users) {
				
				if ($users->isEmpty()) return false;
				
				/**
				 * @var User $user
				 */
				foreach ($users as $user) {
					
					$recordsChildrenCount = (int)$this->allStormChildrenCount($user);
					$moreThanLastDay = $this->moreThanLastDayCount($user, $recordsChildrenCount);
					$moreThanFirstDay = $this->moreThanFirstDayCount($user, $recordsChildrenCount);
					
					$user->goldChildren()->create([
						'records_children_count' => $recordsChildrenCount,
						'more_than_last_day' => $moreThanLastDay,
						'more_than_first_day' => $moreThanFirstDay,
					]);
					
					usleep(10);
				}
				
				return true;
				
			}, 'desc');
	}
	
	public function __invoke()
	{
		Dinglog::text("========== Start counting gold children......");
		
		$this->count();
		
		Dinglog::text("========== Gold children counted......");
	}
}
